<template>
  <div  >
    {{roomMassage}}
    <br>
    <div v-for="item in userList">
      <img :src="item.headimgurl" alt="" style="width:80px;">
      <div>{{item.nickname}}</div>
      <div>{{item.num||0}}</div>
    </div>
      <pre>
    </pre>
    <button @click="startShake"> 开始 </button>
  </div>
</template>

<script>

export default  {
  
  name: 'ShakeAdmin',

  mixins: [],

  components: {},

  props: {
    
  },

  data() {
    return {
      ws:null,
      roomId:1,
      roomMassage:'管理员驾到',
      userList:[],
      shakeList:{},
    };
  },

  computed: {},

  watch: {},

  created() {},

  mounted() {
    this.init();
  },

  destroyed() {
    this.ws.close();
  },

  methods: {
    startShake(obj){
      let tpl={
        module:'ShakeService',
        action:'startShake',
        data:{ roomId:this.roomId }
      };
      this.ws.send(JSON.stringify(tpl));
    },
    /*接收用户发来的摇一摇数据*/
    receiveSendNum(obj){
      this.shakeList={...this.shakeList,[obj.userInfo.openid]:obj.num};
    },
    /*连接房间成功*/
    receiveBuildRoom(obj){
      this.roomMassage=obj.data.massage;
    },
    /*取得所有房间内成员*/
    receiveAllUserSessions(obj){
      let arr=[];
      Object.keys(obj.data).forEach((key)=>{
        arr.push(obj.data[key].userInfo);
      });
      this.userList=arr;
    },
    /*当用户加入房间*/
    receiveAddRoom(obj){
      let a=this.userList.find((item)=>{
        if( !item.openid ) return false;
        return item.openid == obj.userInfo.openid;
      });
      if(!a)
        this.userList.push(obj.userInfo);
    },
    init(){
      let ws=new WebSocket("wss://www.wyx2013.cn/wss");
      ws.onopen = () =>{
        let tpl={
            module:'ShakeService',
            action:'buildRoom',
            data:{ roomId:this.roomId,token:'dsfffsdfety54' }
        };
        ws.send(JSON.stringify(tpl));
      }
      ws.onmessage= (e)=> {
        let obj,fn,raw;
        if(typeof e.data =='string' &&  e.data.substring(0,1)=='{' ){
          raw = e.data.replace(/\\([^u])/g, '$1');
          obj=eval('(' + e.data + ')'); 
          //obj=JSON.parse(raw);
          fn='receive'+obj.type;
          this[fn](obj);
        }
      }
      ws.onerror=()=>{
        this.roomMassage='房间关闭或退出';
        this.userList=[];
        this.init();
      }
      ws.onclose=()=>{
        this.roomMassage='房间关闭或退出';
        this.userList=[];
        this.init();
      }
      this.ws=ws;
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style >
.img{

}
</style>
